package com.mrjy.maintain.bo;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.solr.common.SolrInputDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.mrjy.common.entity.DistributorInfo;
import com.mrjy.common.entity.PolyInfo;
import com.mrjy.common.entity.ServiceStationInfo;
import com.mrjy.common.entity.SolrEntity;
import com.mrjy.common.entity.TeacherInfo;
import com.mrjy.common.entity.TeacherInfoTypeRel;
import com.mrjy.common.entity.UserInfo;
import com.mrjy.common.entity.VideoInfo;
import com.mrjy.common.solr.SolrServerClient;
import com.mrjy.common.util.DateUtil;
import com.mrjy.common.util.ExcelUtil;
import com.mrjy.common.util.GlobalConstant;
import com.mrjy.common.util.MD5Encrypt;
import com.mrjy.common.util.PolyvTokenUtil;
import com.mrjy.common.util.RedisUtil;
import com.mrjy.common.util.RegexUtil;
import com.mrjy.common.util.ResultUtil;
import com.mrjy.common.util.SolrUtil;
import com.mrjy.common.util.UpdateDisableFlagUtil;
import com.mrjy.maintain.dao.IServiceStationInfoDao;
import com.mrjy.maintain.dao.ITeacherInfoDao;
import com.mrjy.maintain.dao.ITeacherInfoTypeRelDao;
import com.mrjy.maintain.dao.IUserInfoDao;
import com.mrjy.maintain.dto.MasterListDTO;
import com.mrjy.maintain.dto.TeacherInfoDTO;
import com.mrjy.maintain.dto.TeacherParamDTO;
import com.mrjy.maintain.dto.TeachersHasRecordAuthDTO;
import com.mrjy.maintain.dto.TeachersRecordAuthParamDTO;
import com.mrjy.maintain.util.RoleInfoEnum;
import com.mrjy.share.dao.IDistributorInfoDao;
import com.mrjy.share.dao.IDistributorTeamInfoDao;
import com.mrjy.share.dto.DistributorInfoDTO;
import com.mrjy.video.dao.IVideoInfoDao;
import com.tencent.common.Util;

@Service("teacherInfoBo")
public class TeacherInfoBo implements ITeacherInfoBo{

	@Resource
	private ITeacherInfoDao teacherInfoDao;
	@Resource
	private IDistributorInfoDao distributorInfoDao;
	@Resource
	private IDistributorTeamInfoDao distributorTeamInfoDao;
	@Resource
	private IUserInfoDao userInfoDao;
	@Resource
	private ITeacherInfoTypeRelDao teacherRelDao;
	@Resource
	private IServiceStationInfoDao serviceStationInfoDao;
    @Resource
    private IVideoInfoDao videoInfoDao;
    @Autowired
    private SolrServerClient solrServerClient;


    private Logger LOGGER = LoggerFactory.getLogger(TeacherInfoBo.class);

	@Override
	public Object txInsert(TeacherInfoDTO info,HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		if (StringUtils.isBlank(info.getUserName())) {
			map.put("err_code", 401);
			map.put("err_msg", "讲师名称不能为空");
			return map;
		}
		if (StringUtils.isNotBlank(info.getUserName()) &&
				info.getUserName().length()>16) {
			map.put("err_code", 408);
			map.put("err_msg", "讲师名称过长(小于16个字符)");
			return map;
		}
		if (StringUtils.isNotBlank(info.getMobilePhone()) && 
				!RegexUtil.checkMobile(info.getMobilePhone())) {
			map.put("err_code", 410);
			map.put("err_msg", "手机号格式不正确");
			return map;
		}
		/*if (StringUtils.isNotBlank(info.getBankCard()) && 
				!RegexUtil.checkICBC(info.getBankCard())) {
			map.put("err_code", 409);
			map.put("err_msg", "银行卡格式不正确,请填写正确的工商银行卡号");
			return map;
		}*/
		if (StringUtils.isBlank(info.getPicName())) {
			map.put("err_code", 402);
			map.put("err_msg", "讲师头像不能为空");
			return map;
		}
		if (StringUtils.isBlank(info.getUserDesc())) {
			map.put("err_code", 403);
			map.put("err_msg", "讲师简介不能为空");
			return map;
		}
		if (info.getTypeIds() == null || info.getTypeIds().length == 0) {
			map.put("err_code", 404);
			map.put("err_msg", "讲师标签不能为空");
			return map;
		}
		if (info.getTypeIds().length > 10) {
			map.put("err_code", 405);
			map.put("err_msg", "讲师标签不能大于10个");
			return map;
		}
//		if (StringUtils.isBlank(info.getTeacherType())) {
//			map.put("err_code", 406);
//			map.put("err_msg", "讲师分成不能为空");
//			return map;
//		}
		if (info.getSharingProportion() == null) {
			map.put("err_code", 406);
			map.put("err_msg", "分成比例不能为空");
			return map;
		}
		if (StringUtils.isBlank(info.getSex())) {
			map.put("err_code", 407);
			map.put("err_msg", "讲师性别不能为空");
			return map;
		}
		if(StringUtils.isNotBlank(info.getLoginCode())){
			UserInfo ui = userInfoDao.queryByLoginCode(info.getLoginCode());
			if(ui != null){
				map.put("err_code", 202);
				map.put("err_msg", "该账号已存在！,请重新填写账户");
				return map;
			}
		}
		
		UserInfo userInfo = userInfoDao.queryByMobilePhone(info.getMobilePhone());
		
		if(userInfo != null  ){
			TeacherInfo vo = new TeacherInfo();
			vo.setUserId(userInfo.getId());
			vo.setDisableFlag(0);
			if (teacherInfoDao.queryByUserId(vo) != null) { //该教师已存在
				map.put("err_code", 204);
				map.put("err_msg", "该讲师已存在");
				return map;
			}
			if(userInfo.getRoleId().intValue() != RoleInfoEnum.STUDENT.getRoleId() 
					&& userInfo.getRoleId().intValue() != RoleInfoEnum.SERVICE_ADMIN.getRoleId()){//不是普通用户和服务站
				map.put("err_code", 203);
				map.put("err_msg", "该手机已经被其他角色（非普通用户和服务站）使用，请换个手机号码试试");
				return map;
			}else {
				if(userInfo.getRoleId().intValue() == RoleInfoEnum.SERVICE_ADMIN.getRoleId()){
					//如果服务站还有效，则不修改原本服务站的信息
					if(null != userInfo.getStationId()){
						ServiceStationInfo ssi = serviceStationInfoDao.queryById(userInfo.getStationId());
						if(ssi != null && ssi.getDeadlineTime().getTime() > System.currentTimeMillis()){
							//有效期内
							TeacherInfo teacherInfo = teacherInfoDao.queryByMobilePhone(info.getMobilePhone());
							if (teacherInfo!=null) {
								map.put("err_code", 205);
								map.put("err_msg", "该手机号已被注册为讲师");
								return map;
							}
						}
					}
				}
				if (userInfo.getRoleId().intValue() == RoleInfoEnum.STUDENT.getRoleId()) {
					userInfo.setLoginCode(info.getLoginCode());
					userInfo.setUserName(info.getUserName());
					if(StringUtils.isBlank(userInfo.getRecommendCode())){
						userInfo.setRecommendCode(userInfoDao.generateRecommendCodeOne(8));
					}
					userInfo.setSex(info.getSex());
					userInfo.setEmail(info.getEmail());
					userInfo.setMobilePhone(info.getMobilePhone());
					userInfo.setIdCard(info.getIdCard());
					userInfo.setUserDesc(info.getUserDesc());
					userInfo.setPicName(info.getPicName());
					userInfo.setBankCard(info.getBankCard());
					userInfo.setRoleId(RoleInfoEnum.TEACHER.getRoleId());
					if(userInfo.getPassword() != null){
						userInfo.setPassword(MD5Encrypt.encryptByMD5("123abc"));
					}
					userInfoDao.updateById(userInfo);
				}
			}
		}else {
			userInfo = new UserInfo();
			userInfo.setRoleId(RoleInfoEnum.TEACHER.getRoleId());
			userInfo.setUserName(info.getUserName());
			userInfo.setRecommendCode(userInfoDao.generateRecommendCodeOne(8));
			userInfo.setSex(info.getSex());
			userInfo.setEmail(info.getEmail());
			userInfo.setMobilePhone(info.getMobilePhone());
			userInfo.setIdCard(info.getIdCard());
			userInfo.setUserDesc(info.getUserDesc());
			userInfo.setPicName(info.getPicName());
			userInfo.setPassword(MD5Encrypt.encryptByMD5("123abc"));
			userInfo.setRegisterDate(new Date().getTime());
			userInfo.setDisableFlag(0);
			userInfo.setBankCard((info.getBankCard()));
			userInfoDao.insert(userInfo);
		}
		
		
		//插入分类标签记录
		if (info.getTypeIds()!=null && info.getTypeIds().length>0) {
			//先删除之前的记录
            teacherRelDao.deleteByTeacherId(userInfo.getId());
			for (Integer typeId : info.getTypeIds() ) {
				TeacherInfoTypeRel teacherInfoRel = new TeacherInfoTypeRel();
				teacherInfoRel.setTypeId(typeId);
				teacherInfoRel.setTeacherId(userInfo.getId());
				teacherRelDao.insert(teacherInfoRel);
			}
		}
		//添加teacherInfo
		TeacherInfo ti = new TeacherInfo();
		ti.setUserId(userInfo.getId());
		ti.setTeacherType(info.getTeacherType());
		ti.setSharingProportion(info.getSharingProportion());
		ti.setCreateTime(new Timestamp(System.currentTimeMillis()));
		ti.setRecordAuthority(info.getRecordAuthority()); //语音权限
		ti.setAskedPrice(BigDecimal.valueOf(9.9));//默认9.9
		ti.setDisableFlag(0);
		ti.setMiniDesc(info.getMiniDesc());
		int row = teacherInfoDao.insert(ti);
		if (row>0) {
			//添加讲师索引
			try{
				SolrEntity entity = new SolrEntity();
				entity.setId("teacher_"+ti.getId());
				entity.setTeacherId(ti.getId());
				entity.setUserId(ti.getUserId());
				entity.setTeacherName(info.getUserName());
				entity.setTeacherDesc(info.getUserDesc());
				entity.setTeacherTypes(SolrUtil.formatVideoTypes(info.getTypeIds()));
				entity.setRecordAuthority(info.getRecordAuthority());
				entity.setPicName(info.getPicName());
				UserInfo _user = userInfoDao.queryByIdForBack(ti.getUserId());
				entity.setHeadImgUrl(_user==null?null:_user.getHeadImgUrl());
	    		solrServerClient.add(entity);
	    		map.put("solr_msg", "索引插入成功");
	    	} catch (Exception e) {
	    		e.printStackTrace();
	    		LOGGER.debug("[索引插入失败]："+e.getMessage());
	    		map.put("solr_msg", "索引插入失败");
	    		map.put("err_code", 500);
	    		map.put("err_msg", "添加失败");
	    		TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	    		return map;
	    	}
			
			//新增一条为老师身份的推广者记录
			DistributorInfo dInfo = new DistributorInfo();
			dInfo.setUserId(userInfo.getId());
			dInfo.setDistributorName(userInfo.getUserName());
			dInfo.setMobilePhone(userInfo.getMobilePhone());
			dInfo.setCreateTime(new Timestamp(System.currentTimeMillis()));
			dInfo.setShareCode(userInfo.getRecommendCode());
			dInfo.setBankCard(userInfo.getBankCard());
			if("0".equals(info.getTeacherType())){
				dInfo.setDistributorType("51");//明师
			}else if("1".equals(info.getTeacherType())){
				dInfo.setDistributorType("52");//讲师
			}
			dInfo.setSharingProportion(info.getSharingProportion());
			dInfo.setDisabledFlag(0);
			distributorInfoDao.insert(dInfo);
			map.put("err_code", 200);
			map.put("err_msg", "添加成功");
		}else {
			map.put("err_code", 500);
			map.put("err_msg", "添加失败");
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		}
		return map;
	}

	@Override
	public int txDeleteByIds(int[] ids) {
		return teacherInfoDao.deleteByIds(ids);
	}

	@Override
	public Object txUpdateById(TeacherInfoDTO info,HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		if (StringUtils.isBlank(info.getUserName())) {
			map.put("err_code", 401);
			map.put("err_msg", "讲师名称不能为空");
			return map;
		}
		if (StringUtils.isNotBlank(info.getUserName()) &&
				info.getUserName().length()>16) {
			map.put("err_code", 408);
			map.put("err_msg", "讲师名称过长(小于16个字符)");
			return map;
		}
		if (StringUtils.isNotBlank(info.getMobilePhone()) && 
				!RegexUtil.checkMobile(info.getMobilePhone())) {
			map.put("err_code", 410);
			map.put("err_msg", "手机号格式不正确");
			return map;
		}
		/*if (StringUtils.isNotBlank(info.getBankCard()) && 
				!RegexUtil.checkICBC(info.getBankCard())) {
			map.put("err_code", 409);
			map.put("err_msg", "银行卡格式不正确,请填写正确的工商银行卡号");
			return map;
		}*/
		if (StringUtils.isBlank(info.getPicName())) {
			map.put("err_code", 402);
			map.put("err_msg", "讲师头像不能为空");
			return map;
		}
		if (StringUtils.isBlank(info.getUserDesc())) {
			map.put("err_code", 403);
			map.put("err_msg", "讲师简介不能为空");
			return map;
		}
		if (info.getTypeIds() == null || info.getTypeIds().length == 0) {
			map.put("err_code", 404);
			map.put("err_msg", "讲师标签不能为空");
			return map;
		}
		if (info.getTypeIds().length > 10) {
			map.put("err_code", 405);
			map.put("err_msg", "讲师标签不能大于10个");
			return map;
		}
//		if (StringUtils.isBlank(info.getTeacherType())) {
//			map.put("err_code", 406);
//			map.put("err_msg", "讲师分成不能为空");
//			return map;
//		}
		if (info.getSharingProportion() == null) {
			map.put("err_code", 406);
			map.put("err_msg", "分成比例不能为空");
			return map;
		}
		if (StringUtils.isBlank(info.getSex())) {
			map.put("err_code", 407);
			map.put("err_msg", "讲师性别不能为空");
			return map;
		}
		UserInfo userInfo = userInfoDao.queryByIdForBack(info.getUserId());
		UserInfo existInfo = userInfoDao.queryByMobilePhone(info.getMobilePhone());
		if(existInfo != null  ){  
			if(existInfo.getId().intValue() != info.getUserId().intValue()){ //手机号被修改, 存在记录
				if (existInfo.getRoleId().intValue() == RoleInfoEnum.SERVICE_ADMIN.getRoleId() && null != existInfo.getStationId()) {
					if (teacherInfoDao.queryByMobilePhone(info.getMobilePhone())==null) {
						map.put("err_code", 204);
						map.put("err_msg", "该手机已注册为服务站,若想成为讲师,请直接添加讲师");
						return map;
					} 
				}else {
					map.put("err_code", 203);
					map.put("err_msg", "该手机已经被使用，请换个手机号码试试");
					return map;
				}
			}
		}else {  //手机号被修改, 不存在记录
			
		}
		
		//插入分类标签记录
		if (info.getTypeIds()!=null && info.getTypeIds().length>0) {
			//先删除之前的记录
            teacherRelDao.deleteByTeacherId(info.getUserId());
			for (Integer typeId : info.getTypeIds() ) {
				TeacherInfoTypeRel teacherInfoRel = new TeacherInfoTypeRel();
				teacherInfoRel.setTypeId(typeId);
				teacherInfoRel.setTeacherId(info.getUserId());
				teacherRelDao.insert(teacherInfoRel);
			}
		}
		userInfo.setMobilePhone(info.getMobilePhone());
		userInfo.setLoginCode(info.getLoginCode());
		userInfo.setUserName(info.getUserName());
		userInfo.setSex(info.getSex());
		userInfo.setEmail(info.getEmail());
		userInfo.setIdCard(info.getIdCard());
		userInfo.setUserDesc(info.getUserDesc());
		userInfo.setPicName(info.getPicName());
		userInfo.setBankCard(info.getBankCard());
		if(userInfo.getPassword() != null){
			userInfo.setPassword(MD5Encrypt.encryptByMD5("123abc"));
		}
		userInfoDao.updateById(userInfo);
		
		//更新teacherInfo
		TeacherInfo ti = new TeacherInfo();
		ti.setUserId(info.getUserId());
		ti.setTeacherType(info.getTeacherType());
		ti.setSharingProportion(info.getSharingProportion());
		ti.setRecordAuthority(info.getRecordAuthority());
		ti.setMiniDesc(info.getMiniDesc());
		int row = teacherInfoDao.updateByUserId(ti);
		if (row > 0) {
			//更新讲师索引
			try{
				SolrInputDocument document = new SolrInputDocument();
        		document.addField("id", "teacher_"+info.getId());
        		document.addField("userId", info.getUserId());
        		document.addField("teacherId", info.getId());
        		document.addField("teacherName", info.getUserName());
        		document.addField("teacherDesc",  info.getUserDesc());
        		document.addField("teacherTypes", SolrUtil.formatVideoTypes(info.getTypeIds()));
        		UserInfo _user = userInfoDao.queryByIdForBack(ti.getUserId());
        		document.addField("headImgUrl", _user==null?null:_user.getHeadImgUrl());
        		document.addField("picName", info.getPicName());
        		document.addField("recordAuthority", info.getRecordAuthority());
        		solrServerClient.addDoc(document);
	    		map.put("solr_msg", "索引更新成功");
	    	} catch (Exception e) {
	    		e.printStackTrace();
	    		LOGGER.debug("[索引更新失败]："+e.getMessage());
	    		map.put("solr_msg", "索引更新失败");
	    		map.put("err_code", 500);
	    		map.put("err_msg", "更新失败");
	    		TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	    		return map;
	    	}
			//更新推广者表
			Map<String,Object> paramMap = new HashMap<String,Object>();
			paramMap.put("userId", userInfo.getId());
			paramMap.put("disabledFlag", 0);
			paramMap.put("distributorTypes", new String[]{"51","52"});
			List<DistributorInfoDTO> dInfoList = distributorInfoDao.queryByMap(paramMap);
			if(dInfoList != null && dInfoList.size() > 0){
				StringBuilder builder = new StringBuilder();
				if("0".equals(info.getTeacherType())){
					builder.append("52");
				}else if("1".equals(info.getTeacherType())){
					builder.append("51");
				}
				DistributorInfo dInfo = new DistributorInfo(); 
				dInfo.setId(dInfoList.get(0).getId());
				dInfo.setDistributorName(info.getUserName());
				dInfo.setSharingProportion(info.getSharingProportion());
				dInfo.setDistributorType(builder.toString());
				dInfo.setMobilePhone(info.getMobilePhone());
				dInfo.setBankCard(info.getBankCard());
				distributorInfoDao.updateById(dInfo);
			}
			map.put("err_code", 200);
			map.put("err_msg", "更新成功");
		}else {
			map.put("err_code", 500);
			map.put("err_msg", "更新失败");
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		}
		return map;
	}

	@Override
	public TeacherInfoDTO queryById(int id) {
		TeacherInfoDTO dto = teacherInfoDao.queryById(id);
		if(dto != null && dto.getUserId() != null){
			List<TeacherInfoTypeRel> list = teacherRelDao.selectListByTeacherId(dto.getUserId());
			if(list != null && list.size() > 0){
				Map<Integer , String> typeMap = new HashMap<Integer , String>();
				StringBuffer typeIds = new StringBuffer();
				for(int i = 0 ; i < list.size(); i++){
					TeacherInfoTypeRel rel = list.get(i);
					typeMap.put(rel.getId(), rel.getTypeName());
					if(i == list.size()-1){
						typeIds.append(rel.getTypeId());
					}else{
						typeIds.append(rel.getTypeId()).append("@_@");
					}
				}
				dto.setTypeMap(typeMap);
				//dto.setTypeIds(typeIds.toString());
			}
		}
		
		return dto;
	}

	@Override
	public Object queryPage(TeacherInfoDTO dto,HttpSession session) {
		Map<String,Object> map = new HashMap<String,Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		int count = teacherInfoDao.querySumTeacherInfo(dto);
		//全站讲师数
		TeacherInfoDTO vo= new TeacherInfoDTO();
		if(count > 0){
			List<TeacherInfoDTO> list = teacherInfoDao.queryPage(dto);
			if(null != list && list.size() > 0){
				map.put("err_code", 0);
				map.put("err_msg", "查询成功");
				map.put("rows", list);
				map.put("total", count);
                map.put("totalTeacher", count);
            }else {
				map.put("err_code", 1);
				map.put("err_msg", "无数据");
				map.put("rows", list);
				map.put("total", 0);
                map.put("totalTeacher", count);
            }
		}else{
			map.put("err_code", 2);
			map.put("err_msg", "无数据");
			map.put("rows", null);
			map.put("total", 0);
            map.put("totalTeacher", count);
        }
		
		return map;
	}

	@Override
    public Object txUpdateDisableFlag(TeacherInfo info,HttpSession session){
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		int row = 0;
		if(info == null){
			row = -1;
			map.put("err_code", 400);
			map.put("err_msg", "参数错误");
			return map;
		}
		if (info.getIds()==null||info.getIds().length==0) {
			map.put("err_code", 401);
			map.put("err_msg", "请勾选要操作的记录");
			return map;
		}
		if(info.getIds() != null){ //前端传过来的就是userId数组  例: ids=[8663,8664]
			String[] distributorTypes = {"51","52"};
			for(int i =0; i<info.getIds().length; i++){
				UpdateDisableFlagUtil.updateDisableFlagForTeam(distributorTypes,
						info.getIds()[i], info.getDisableFlag());
			}
            if (info.getIds() != null && info.getIds().length > 0 && info.getDisableFlag() != null) {
                for(Integer id : info.getIds()){
                	UserInfo ui = new UserInfo();
    				ui.setId(id);
                    if (info.getDisableFlag().equals(1)) {
                        ui.setRoleId(4);
                    } else if (info.getDisableFlag().equals(0)) {
                        ui.setRoleId(2);
                    }
                    userInfoDao.updateById(ui);
                }
            	
            }
        }
		row = teacherInfoDao.updateDisableFlag(info);
		if (row>0) {
			if (info.getDisableFlag().intValue() == 0) {
				//数据库启用,添加索引
				try {
					TeacherInfoDTO teacher = new TeacherInfoDTO();
					for (Integer userId : info.getIds()) {
						SolrEntity teacherEntity = new SolrEntity();
						teacher.setUserId(userId);
						teacher.setDisableFlag(null);
						teacher =  (TeacherInfoDTO) teacherInfoDao.queryByUserId(teacher);
						teacherEntity.setId("teacher_"+teacher.getId());
						teacherEntity.setUserId(userId);
						teacherEntity.setTeacherId(teacher.getId());
						teacherEntity.setTeacherName(teacher.getUserName());
						teacherEntity.setTeacherDesc(teacher.getUserDesc());
						teacherEntity.setTeacherTypes(teacher.getTypeName());
						teacherEntity.setRecordAuthority(teacher.getRecordAuthority());
						teacherEntity.setHeadImgUrl(teacher.getHeadImgUrl());
						teacherEntity.setPicName(teacher.getPicName());
	                	solrServerClient.add(teacherEntity);
					}
					map.put("solr_msg", "索引添加成功");
				} catch (Exception e) {
					e.printStackTrace();
					LOGGER.debug("[索引添加失败]："+e.getMessage());
					map.put("solr_msg", "索引添加失败");
					map.put("err_code", 500);
		            map.put("err_msg", "操作失败");
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return map;
				}
			}else if (info.getDisableFlag().intValue() == 1) {
				//数据库禁用,要删除索引
				try {
					TeacherInfoDTO teacher = new TeacherInfoDTO();
					for (Integer userId : info.getIds()) {
						teacher.setUserId(userId);
						teacher.setDisableFlag(null);
						teacher =  (TeacherInfoDTO) teacherInfoDao.queryByUserId(teacher);
						solrServerClient.deleteById("teacher_"+teacher.getId());
					}
					map.put("solr_msg", "索引删除成功");
				} catch (Exception e) {
					e.printStackTrace();
					LOGGER.debug("[索引删除失败]："+e.getMessage());
					map.put("solr_msg", "索引删除失败");
					map.put("err_code", 500);
		            map.put("err_msg", "操作失败");
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return map;
				}
			}
			map.put("err_code", 200);
			map.put("err_msg", "操作成功,"+row+"条记录受影响");
		}else {
			map.put("err_code", 500);
			map.put("err_msg", "操作失败,"+row+"条记录受影响");
		}
        return map;
    }

    @Override
    public Object queryByUserId(TeacherInfo info) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        TeacherInfo teacherInfo = teacherInfoDao.queryByUserId(info);
        paramMap.put("info", teacherInfo);
        paramMap.put("status", 200);
        return paramMap;
    }

    @Override
    public Object txUpdateByUserId(TeacherInfo info) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        int teacherInfo = teacherInfoDao.txUpdateByUserId(info);
        if (teacherInfo > 0) {
            paramMap.put("err_msg", "更新成功");
            paramMap.put("err_code", 0);
        } else {
            paramMap.put("err_msg", "更新失败");
            paramMap.put("err_code", 1);
        }
        return paramMap;
    }

	@Override
	public Object exportExl(TeacherInfoDTO dto, HttpServletResponse response,HttpSession session){
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		List<TeacherInfoDTO> dataset = teacherInfoDao.queryPage(dto);
		if (dataset == null || dataset.size()==0) {
			map.put("err_code", 404);
			map.put("err_msg", "无可导出数据");
			return map;
		}
		try {
			ExcelUtil.writeExcel(response, "讲师"+DateUtil.dateToString(new Date(), DateUtil.FULL_DATE_STR)+".xls", dataset, TeacherInfoDTO.class);
			map.put("err_code", 200);
			map.put("err_msg", "导出成功");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("err_code", 500);
			map.put("err_msg", "导出失败");
		}
		return map;
	}

    @Override
    public Object txDeleteTeacherByIds(int[] ids) {
        Map<String, Object> map = new HashMap<String, Object>();
        
      //数据库删除,要删除索引
		try {
			TeacherInfoDTO teacher = new TeacherInfoDTO();
			for (Integer userId : ids) {
				teacher.setUserId(userId);
				teacher =  (TeacherInfoDTO) teacherInfoDao.queryByUserId(teacher);
				solrServerClient.deleteById("teacher_"+teacher.getId());
			}
			map.put("solr_msg", "索引删除成功");
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.debug("[索引删除失败]："+e.getMessage());
			map.put("solr_msg", "索引删除失败");
			map.put("err_code", 1);
            map.put("err_msg", "删除失败");
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return map;
		}
        
        int result = teacherInfoDao.deleteTeacherByIds(ids);
        if (result > 0) {
        	Map<String , Object> paramMap = new HashMap<String , Object>() ;
        	paramMap.put("typeItems", new String[]{"51","52"}) ;
        	paramMap.put("ids", ids) ;
        	int row = distributorInfoDao.deleteByIds(paramMap);
            map.put("err_msg", "删除成功");
            map.put("err_code", 0);
        } else {
            map.put("err_msg", "删除失败");
            map.put("err_code", 1);
        }
        return map;
    }

    @Override
    public Object queryTeacherWithCourse(VideoInfo vInfo, HttpSession session) {
        Map<String, Object> map = new HashMap<String, Object>();
        UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
        if (null == loginUser) {
            map.put("err_code", -1);
            map.put("err_msg", "用户未登录");
            return map;
        }
        vInfo.setUserId(loginUser.getId());
        List<VideoInfo> list = videoInfoDao.queryTeacherWithCourse(vInfo);
        int total = videoInfoDao.countTeacherWithCourse(vInfo);

        for (VideoInfo videoInfo : list) {
            if (RedisUtil.isVideoVip(loginUser.getId(), videoInfo.getId())) {
                videoInfo.setIsVipStatus("1");//有观看权限
            } else {
                videoInfo.setIsVipStatus("0");
            }
            //查询poly视频接口相关信息
            for (VideoInfo info : list) {
                PolyInfo polyInfo = RedisUtil.cache(info.getId() + "");
                info.setPolyInfo(polyInfo);

                PolyvTokenUtil tokenUtil = null;
                try {
                    tokenUtil = PolyvTokenUtil.cloneSimplePolyInfo(info.getVideoCode(), info.getAudioCode(),
                            Util.getHostIp(Util.getInetAddress()),
                            videoInfo.getUserId() + "", "123", "1225");
                } catch (CloneNotSupportedException e) {
                    e.printStackTrace();
                }
                info.setPolyvTokenUtil(tokenUtil);
                info.setVideoCode(null);
                info.setAudioCode(null);
            }

        }

        if (list.size() > 0) {
            map.put("err_msg", "查询成功");
            map.put("err_code", 0);
            map.put("rows", list);
            map.put("total", total);
        } else {
            map.put("err_msg", "查询失败");
            map.put("err_code", 201);
        }
        return map;
    }

	@Override
	public Object queryTeachersHasRecordAuth(TeachersRecordAuthParamDTO dto) {
		List<TeachersHasRecordAuthDTO> list = teacherInfoDao.queryTeachersHasRecordAuth(dto) ;
		return ResultUtil.success(list);
	}

	@Override
	public Object queryTeacherList(TeacherParamDTO dto) {
		List<MasterListDTO> list = teacherInfoDao.queryTeacherList(dto) ;
		return ResultUtil.success(list);
	}

}
